﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace ET.Score.SharedLibrary
{
    public static class PasswordEncryptor
    {
        /// <summary>
        ///     对密码md5加密后，在新字符串后+"bjdaxiang"再Md5加密一次
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        public static string EncryptPassword(this string password)
        {
            if (string.IsNullOrWhiteSpace(password))
            {
                string passwordAutoCreat = "";
                string str = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
                Random random = new Random(DateTime.Now.Millisecond);

                for (var i = 0; i < 8; i++)
                {
                    passwordAutoCreat += str[random.Next(0, str.Length)];
                }
                password = passwordAutoCreat;
            }
            password = GetMd5OfString(password);
            password += "bjdaxiang";
            password = GetMd5OfString(password);
            return password;
        }

        private static string GetMd5OfString(string passwordToEncrypt)
        {
            if (passwordToEncrypt == null)
                throw new ArgumentNullException("passwordToEncrypt");

            var output = GetMd5OfStringInternal(passwordToEncrypt);
            return BitConverter.ToString(output).Replace("-", "");
        }

        // internal compute hash value of a string
        private static byte[] GetMd5OfStringInternal(string passwordToEncrypt)
        {
            Contract.Assert(passwordToEncrypt != null);

            var orgBytes = Encoding.UTF8.GetBytes(passwordToEncrypt);

            // The default hash algorithm is provided by MD5CryptoServiceProvider 
            using (var md5 = MD5.Create())
            {
                var md5Bytes = md5.ComputeHash(orgBytes);
                return md5Bytes;
            }
        }
    }
}
